package com.android.lovely.ui.fragment

import android.os.Bundle
import androidx.core.view.isVisible
import androidx.fragment.app.Fragment
import androidx.fragment.app.FragmentActivity
import androidx.fragment.app.FragmentManager
import androidx.fragment.app.activityViewModels
import androidx.lifecycle.Lifecycle
import androidx.lifecycle.lifecycleScope
import androidx.viewpager2.adapter.FragmentStateAdapter
import coil.load
import com.android.lovely.R
import com.android.lovely.const.ChatChange
import com.android.lovely.const.HomeShowRole
import com.android.lovely.const.HomeShowTask
import com.android.lovely.data.HomeTabData
import com.android.lovely.databinding.FragmentMineBinding
import com.android.lovely.ext.copy
import com.android.lovely.ext.startWebView
import com.android.lovely.framework.BaseFragment
import com.android.lovely.manager.KVStore
import com.android.lovely.ui.activity.LifecycleActivity
import com.android.lovely.ui.activity.OptimizationActivity
import com.android.lovely.ui.activity.PayActivity
import com.android.lovely.ui.activity.SetLovelyActivity
import com.android.lovely.ui.activity.SysMsgActivity
import com.android.lovely.ui.dialog.SignDialog
import com.android.lovely.ui.dialog.UserDialog
import com.android.lovely.ui.viewmodel.MineViewModel
import com.android.lovely.user.UserManager
import com.android.lovely.user.UserManager.registerAuthChange
import com.kotlin.extensions.bus.FlowBus
import com.kotlin.extensions.bus.flowOf
import com.kotlin.extensions.context.ContextExt.startPage
import com.kotlin.extensions.view.ViewExt.addStatusBarMarginTop
import com.kotlin.extensions.view.ViewExt.clickable
import kotlinx.coroutines.launch


/**
 * 我的界面
 * @author why
 * @date 2025/3/9 16:54
 */
class MineFragment : BaseFragment<FragmentMineBinding>() {
    private val mViewModel by activityViewModels<MineViewModel>()

    private var userId = ""

    private val tabs by lazy {
        mutableListOf(
            HomeTabData(null, requireActivity().getString(R.string.works)),
            HomeTabData(null, requireActivity().getString(R.string.task_center)),
            HomeTabData(null, requireActivity().getString(R.string.my_cards)),
        )
    }

    private var currentSelectId = -1

    private val adapter by lazy {
        MinePagerAdapter(childFragmentManager, lifecycle)
    }

    override suspend fun initData() {

    }

    override fun initView() {
        mBinding.rlTop.addStatusBarMarginTop()
        mBinding.viewPager.isUserInputEnabled = false
        mBinding.viewPager.adapter = adapter
        mBinding.viewPager.offscreenPageLimit = adapter.itemCount

        registerAuthChange {
            userId = it.id.toString()
            mBinding.name.setText(it.name)
            mBinding.lifetime.isVisible = UserManager.isB()
            mBinding.lifetime.setImageResource(if (it.isVip()) R.drawable.icon_vip_lifetime else R.drawable.icon_vip_no)
            mBinding.lifecycle.isVisible = UserManager.isB() && UserManager.isVip().not()
            mBinding.ivRole.isVisible = UserManager.isB()
            mBinding.userid.text = getString(R.string.user_id, it.id.toString())
            mBinding.gems.text = it.point.toString()

            if (mBinding.avatar.tag != it.headImg) {
                mBinding.avatar.tag = it.headImg
                mBinding.avatar.load(it.headImg) {
                    placeholder(R.drawable.icon_default_avatar)
                    error(R.drawable.icon_default_avatar)
                    crossfade(true)
                }
            }

            if (UserManager.isB()) {
                mBinding.llTaskCenter.isVisible = true
                mBinding.tvTaskCenter.isVisible = true
                mBinding.ivTaskCenter.isVisible = true
            } else {
                mBinding.llTaskCenter.isVisible = false
                mBinding.tvTaskCenter.isVisible = false
                mBinding.ivTaskCenter.isVisible = false
            }
            changeTab(0)
            mBinding.viewPager.currentItem = 0

        }
        mBinding.lifecycle.clickable {
            startPage<LifecycleActivity>()
        }
        mBinding.lifetime.clickable {
            if (mBinding.lifecycle.isVisible) startPage<LifecycleActivity>()
        }
        mBinding.userid.clickable {
            userId.copy(requireActivity())
        }
        mBinding.ivSetting.clickable {
            startPage<SetLovelyActivity>()
        }
        mBinding.itemRoot.clickable {
            UserDialog().apply {
                arguments = Bundle().apply {
                    putBoolean("canCancel", true)
                }
            }.show(parentFragmentManager)
        }
        mBinding.ivRole.clickable {
            KVStore.system?.contactUsUrl?.let {
                requireActivity().startWebView(getString(R.string.contact_us), it)
            }
        }
        mBinding.ivEdit.clickable {
            startPage<OptimizationActivity>()
        }
        mBinding.ivEmail.clickable {
            startPage<SysMsgActivity>()
        }
        mBinding.checkDay.clickable {
            startPage<SignDialog>()
        }
        mBinding.llWallet.clickable {
            startPage<PayActivity>()
        }
        mBinding.tvWorks.isVisible = true
        mBinding.tvTaskCenter.clickable {
            changeTab(1)
        }
        mBinding.tvMyCard.clickable {
            changeTab(2)
        }
        mBinding.tvWorks.clickable {
            changeTab(0)
        }
        update()
        viewLifecycleOwner.lifecycleScope.launch {
            FlowBus.flowOf<HomeShowRole>().collect {
                changeTab(0)
            }
        }
        viewLifecycleOwner.lifecycleScope.launch {
            FlowBus.flowOf<HomeShowTask>().collect {
                changeTab(0)
            }
        }
        viewLifecycleOwner.lifecycleScope.launch {
            FlowBus.flowOf<ChatChange>().collect {
                update()
            }
        }
    }


    private fun update() {
        adapter.updateTags(
            if (UserManager.isB()) {
                arrayListOf(
                    HomeTabData(0, requireActivity().getString(R.string.works)),
                    HomeTabData(1, requireActivity().getString(R.string.task_center)),
                    HomeTabData(2, requireActivity().getString(R.string.my_cards)),
                )
            } else {
                arrayListOf(
                    HomeTabData(0, requireActivity().getString(R.string.works)),
                    HomeTabData(2, requireActivity().getString(R.string.my_cards)),
                )
            }
        )
        changeTab(0)
    }

    private fun changeTab(id: Int) {
        if (currentSelectId == id) {
            return
        }
        currentSelectId = id
        mBinding.viewPager.setCurrentItem(
            if (mBinding.tvWorks.isVisible) {
                id
            } else {
                id - 1
            }, true
        )
        when (id) {
            0 -> {
                mBinding.tvTaskCenter.isSelected = false
                mBinding.tvMyCard.isSelected = false
                mBinding.tvWorks.isSelected = true
            }

            1 -> {
                mBinding.tvTaskCenter.isSelected = true
                mBinding.tvMyCard.isSelected = false
                mBinding.tvWorks.isSelected = false
            }

            else -> {
                mBinding.tvTaskCenter.isSelected = false
                mBinding.tvMyCard.isSelected = true
                mBinding.tvWorks.isSelected = false
            }
        }
    }

    inner class MinePagerAdapter(fragmentManager: FragmentManager,lifeCircle: Lifecycle) : FragmentStateAdapter(fragmentManager, lifeCircle) {

        fun updateTags(tags: List<HomeTabData>) {
            tabs.clear()
            tabs.addAll(tags)
            notifyDataSetChanged()
        }

        override fun getItemCount(): Int {
            return tabs.size
        }

        override fun createFragment(position: Int): Fragment {
            return when (tabs[position].id) {
                0 -> WorkFragment()
                1 -> TaskFragment()
                else -> MyCardsFragment()
            }
        }


        override fun getItemId(position: Int): Long {
            return tabs[position].hashCode().toLong()
        }

        override fun containsItem(itemId: Long): Boolean {
            return tabs.any { it.hashCode().toLong() == itemId }
        }

    }
}